<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.js"></script>
    <script>
        var Stars = [];
        var speed = 15, mx, my;

        //工厂模式
        //创建star类
        function createStar(){
            //1、原料
            var obj = new Object();
            //2、加工
            obj.x = random(-width/2, width/2);
            obj.y = random(-height/2, height/2);
            obj.z = random(0, width);
            obj._color = [random(10,255), random(10,255), random(10,255)]

            obj.update = function(){
                obj.z = obj.z - speed;
                if(obj.z < 1){
                    obj.x = random(-width/2, width/2);
                    obj.y = random(-height/2, height/2);
                    obj.z = random(0, width);
                }
            }

            obj.show = function(){
                fill(obj._color[0], obj._color[1], obj._color[2]);
                //随着z的减小，sx,sy 是不断增大的，所以每次绘制就逐渐远离屏幕中心
                sx = map(obj.x / obj.z, 0, 1, 0, width);
                sy = map(obj.y / obj.z, 0, 1, 0, height);

                //星星越近，半径越大
                r = map(obj.z, 0, width, 12, 2);
                ellipse(sx, sy, r, r);
            }
            //3、出厂
            return obj;
        }

        function setup() {
            const x = document.body.clientWidth
            const y = document.body.clientHeight
            createCanvas(x,y,P2D);
            for(i = 0 ; i < 300; i++){
                Stars[i] = createStar();
            }
        }

        //通过鼠标反馈速度
        function speedup(){
            if (mouseIsPressed){
                if(speed <= 60){
                speed += 1;
                }
            }else{
                if(speed >= 15){
                speed -= 1;
                }
            }
        }

       function draw() {
           background(0);
           speedup();
           mx = map(mouseX,0,width,-200,200);
           my = map(mouseY,0,height,-200,200);
            //调整坐标中心点位置
           translate(width /2 + mx,height /2 + my);
           for(i = 0; i < Stars.length; i++){
               Stars[i].update();
               Stars[i].show();
           }
       }
    </script>
  </head>
</html>